<template>
  <div>
    <a-modal
      :visible="visible"
      @before-ok="handleOk"
      @ok="handleCancel"
      @cancel="handleCancel"
      ok-text="提交"
      cancel-text="取消"
      title="受理事件"
      title-align="start"
      unmount-on-close
    >
      <a-form
        :model="formValue"
        @submit="handleSubmit"
        layout="vertical"
        size="large"
        ref="formRef"
      >
        <a-form-item
          field="district_id"
          label="选择辖区"
          :rules="[
            { required: true, message: '辖区为必选' }
          ]"
        >
          <a-select
            v-model="formValue.district_id"
            placeholder="请选择辖区..."
            allow-clear
          >
            <a-option
              v-for="o in districts"
              :value="o.id"
              :key="o.id"
            >{{ o.name }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          field="process_by_id"
          label="指派处理民警"
          :rules="[
            { required: true, message: '指派处理民警为必选' }
          ]"
        >
          <a-select
            v-model="formValue.process_by_id"
            placeholder="请选择民警..."
            allow-clear
          >
            <a-option
              v-for="o in acceptors"
              :value="o.id"
              :key="o.id"
            >{{ o.nickname }}</a-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import { cloneDeep, omit } from 'lodash-es'
import { useQuery } from 'villus'
import { useRoute } from 'vue-router'
import gql from 'graphql-tag'

import { useStore } from '/@/store'
import { useGraphqlClient } from '/@/graphql'
import { useApi } from '/@/api'
import { noop } from '/@/utils/helper'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  onClose: {
    type: Function,
    default: () => noop
  }
})
const visible = ref(false)

watch(
  () => props.visible,
  v => {
    visible.value = v
  }, { immediate: true })

const store = useStore()
const route = useRoute()

const formRef = ref()
const formInitValue = {
  status: 'PENDING',
  district_id: null,
  process_by_id: null
}
const formValue = ref(cloneDeep(formInitValue))

const districts = ref([])
const { data, unwatchVariables } = useQuery({
  query: gql`
    query ($id: Int) {
      ie_system_user (
        where: {
          _and: {
            ie_system_user_role: { role: { _eq: "police" } },
            system_user_meta: { system_users_districts: { district_id: { _eq: $id } } }
          }
        }
      ) {
        id
        nickname
      }
    }
  `,
  variables: computed(() => {
    if (formValue.value.district_id) {
      return {
        id: formValue.value.district_id
      }
    }
  }),
  fetchOnMount: false
})

const acceptors = computed(() => {
  return Array.isArray(data.value?.ie_system_user)
    ? data.value?.ie_system_user
    : []
})

watch(
  () => store.userInfo?.system_user_meta?.department?.id,
  department_id => {
    if (department_id) {
      useGraphqlClient().executeQuery({
        query: gql`
          query ($id: Int!) {
            department_districts (args: { department_id: $id }) {
              id
              name
              department {
                id
                name
              }
            }
          }
        `,
        variables: { id: department_id }
      }).then(res => {
        if (!res.error) {
          districts.value = res?.data?.department_districts || []
        }
      })
    }
  }, { immediate: true }
)

function handleCancel() {
  if (formRef.value?.resetFields) {
    formRef.value?.resetFields()
  }
  formValue.value = cloneDeep(formInitValue)
  unwatchVariables()
  props.onClose()
  visible.value = false
}

function handleOk(done) {
  if (formRef.value?.handleSubmit) {
    return formRef.value?.handleSubmit(done)
  }
}

function handleSubmit({ values, errors }, done = noop) {
  if (errors) return done(false)
  useApi()
    .post(
      `ticket/${route.params.id}/update`,
      omit(values, ['district_id']), {
        authorize: true
      }
    )
    .then(res => {
      if (res.code === 0) {
        unwatchVariables()
      }
      done()
    })
}
</script>